from utils_qt.mainwindow import Ui_MainWindow
import sys
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
# import letterbox
import cv2


# 多重继承: 当父类中出现多个自定义的init方法时，多重继承只执行第一个类的init方法，其它不执行。
class UiMain(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(UiMain, self).__init__(parent)
        self.setupUi(self)
        # 图片自适应显示
        self.label_WholeScene.setScaledContents(True)
        self.label_DetectedResults.setScaledContents(True)
        # 功能1：实时更新系统时间
        self.my_timer()
        # 功能2：开始按钮，点击连接TCP
        self.pushButton_Start.clicked.connect(self.start)       # 按钮绑定事件
        self.init_flag = False
        # 功能3：退出按钮
        self.pushButton_Quit.clicked.connect(self.returnToPrevious)


    # 自添加的qt初始化函数
    # 功能1：实时更新系统时间
    def my_timer(self):
        # 定时器，每隔一秒更新系统时间
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)
        # self.Imglabel.setScaledContents(True)  # 图片自适应显示
    def updateTime(self):
        self.label_Time.setText('系统时间：' + QtCore.QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss'))

    # 功能2：开始按钮，点击连接TCP
    def start(self):
        self.init_flag = True

    # 功能3：退出按钮
    def returnToPrevious(self):
        self.close()

    # 功能4：更新label窗口图像
    def update_img(self, img, label_name, flag):
        # img = cv2.imread("bus.jpg")
        # 转换成QT能显示的图像格式
        result_qt = self.cvimg_to_qtimg(img)
        # resize（将图像缩放至与窗口大小适应）
        # jpg = QtGui.QPixmap(result_qt).scaled(self.Imglabel.width(), self.Imglabel.height())
        jpg = QtGui.QPixmap(result_qt)
        # show
        # if flag == "1":
        if label_name == "WholeScene":
            self.label_WholeScene.setPixmap(jpg)        # 更新“全景图”
        else:
            self.label_DetectedResults.setPixmap(jpg)   # 更新“检测结果”

    def cvimg_to_qtimg(self, cvimg):
        height, width, depth = cvimg.shape
        cvimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB)
        cvimg = QImage(cvimg.data, width, height,
                       width * depth,  # 每行数据个数，3通道 所以width*3
                       QImage.Format_RGB888)
        return cvimg

    # 打开文件功能
    # def loadImage(self):
    #     self.fname, _ = QFileDialog.getOpenFileName(self, '请选择图片','.','图像文件(*.jpg *.jpeg *.png, *.mp4)')
    #     if self.fname:
    #         print(self.fname)
    #         self.Infolabel.setText("文件打开成功\n"+self.fname)
    #
    #         # 假如读取的文件是.mp4后缀
    #         if self.fname.endswith(".mp4"):
    #             # result = detectVideo(self.fname)
    #
    #             img_size = 640
    #             stride = 32
    #
    #
    #             with torch.no_grad():
    #                 video = cv2.VideoCapture(self.fname)
    #                 while True:
    #                     ret, frame = video.read()
    #                     # cv2.imshow('Frame', frame)
    #                     # cv2.waitKey(1)
    #                     img0 = frame  # BGR
    #                     # Padded resize
    #                     img = letterbox(img0, img_size, stride=stride)[0]
    #
    #                     # Convert
    #                     img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
    #                     img = np.ascontiguousarray(img)     # 将一个内存不连续存储的数组转换为内存连续存储的数组，使得运行速度更快。
    #
    #                     # predict
    #                     # result,label_list = detectvideo(img, img0)
    #
    #
    #                     result_qt = cvimg_to_qtimg(result)
    #                     jpg = QtGui.QPixmap(result_qt).scaled(self.Imglabel.width(), self.Imglabel.height())
    #
    #                     self.Imglabel.setPixmap(jpg)
    #                     print(label_list)
    #
    #                     # label = ""
    #                     # for i in label_list:
    #                     #     label = label + i + " "
    #                     name_list = [i.split(' ')[0] for i in label_list]
    #                     # print(name_list)
    #
    #                     # 统计列表当中元素有多少个
    #                     # list = [1, 2, 1, 2, 3, 3, 4, 5, 4]
    #                     dict = {}
    #                     for key in name_list:
    #                         dict[key] = dict.get(key, 0) + 1
    #                     print(dict)
    #
    #                     label = str(dict)
    #
    #                     self.Infolabel.setText(label)
    #
    #
    #
    #
    #
    #         else:
    #             result = detectImage(self.fname)
    #
    #         result_qt = cvimg_to_qtimg(result)
    #
    #         print(result_qt)
    #         jpg = QtGui.QPixmap(result_qt).scaled(self.Imglabel.width(), self.Imglabel.height())
    #
    #         self.Imglabel.setPixmap(jpg)
    #
    #
    #         # self.Imglabel.setText(result)
    #
    #
    #
    #     else:
    #         # print("打开文件失败")
    #         self.Infolabel.setText("打开文件失败")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = UiMain()
    ui.show()
    sys.exit(app.exec_())
